const TreeNode = require('./binary_tree_chain')

/**
 * 二叉树的遍历
 */

 const a = new TreeNode('A')
 const b = new TreeNode('B')
 const c = new TreeNode('C')
 const d = new TreeNode('D')
 const e = new TreeNode('E')
 const f = new TreeNode('F')
 const g = new TreeNode('G')
 const h = new TreeNode('H')

 a.leftChild = b
 a.rightChild = c
 b.leftChild = d
 b.rightChild = e
 e.leftChild = g
 e.rightChild = h
 c.leftChild = f
 
//  console.log(JSON.stringify(a))

/**
 * 二叉树的先序遍历
 */

 function preOrder(node) {
     if (!node) {
         return
     }
     console.log(node.data)
     preOrder(node.leftChild)
     preOrder(node.rightChild)
 }


 /**
  * 中序遍历
  * @param {*} node 
  */
 function inOrder(node) {
     if (!node) {
         return
     }
     inOrder(node.leftChild)
     console.log(node.data)
     inOrder(node.rightChild)
 }

/**
 * 后序遍历
 * @param {*} node 
 */
 function postOrder(node) {
     if (!node) {
         return
     }
     postOrder(node.leftChild)
     postOrder(node.rightChild)
     console.log(node.data)
 }


 /**
  * 层次遍历
  * 采用队列来实现
  * @param {*} node 
  */
 function levelOrder(node) {
    if (!node) {
        return
    }
    const queue = [node]
    while(queue.length) {
        let e = queue.shift()
        console.log(e.data)
        if (e.leftChild !== null) {
            queue.push(e.leftChild)
        }
        if (e.rightChild !== null) {
            queue.push(e.rightChild)
        }
    }
 }

 levelOrder(a)
 